package _38CountAndSay;

public class CSolution {

  public static void main(String[] args) {
    System.out.println("aa");
    System.out.println(countAndSay(1));
    System.out.println(countAndSay(2));
    System.out.println(countAndSay(3));
    System.out.println(countAndSay(4));
    System.out.println(countAndSay(5));
  }

  private static String countAndSay(int n) {
    String old = "1";
    if (n == 1) {
      return old;
    }
    for (int i = 2; i <= n; i++) {
      old = process(old);
    }
    return old;
  }

  private static String process(String old) {
    StringBuilder builder = new StringBuilder();
    char[] oldChars = old.toCharArray();
    int count;
    char thisOne;
    for (int i = 0; i < oldChars.length; ) {
      thisOne = oldChars[i++];
      count=1;
      while (i <= oldChars.length - 1 && oldChars[i] == thisOne) {
        count++;
        i++;
      }
      builder.append(count).append(thisOne);
    }
    return builder.toString();
  }
}
